namespace Vanilla

import System.Collections
import System.Threading

class EventLoop:
	# The thread that's running this event loop
	public Thread as Thread
	
	# The queue of events to handle
	public Queue as Queue
	
	# Constructor
	def constructor ():
		Queue = Queue.Synchronized(Queue())
	
	# Runs the event queue
	virtual def Run ():
		Thread = Thread.CurrentThread
		
		while true:
			# Handle all the events we have
			while Queue.Count > 0:
				try:
					Handle(Queue.Dequeue())
				except e:
					print "-WARNING- unhandled exception while handling event:"
					print e
			# Then pause the thread (it will be unpaused when an event is added)
			Thread.Suspend()
	
	# Used from another thread, to wait until all queued events are handled
	virtual def WaitUntilPendingEventsAreHandled ():
		while Queue.Count > 0:
			Thread.CurrentThread.Sleep(100)
	
	# Add an event to the queue [can be called from another thread]
	virtual def Do (e as object):
		Queue.Enqueue(e)
		unless Thread is null:
			Thread.Resume() if Thread.ThreadState == ThreadState.Suspended
	
	# Handles given event [this can/should be overriden]
	protected virtual def Handle (e as object):
		if e isa callable:
			c = e as callable
			c()
		else:
			print "-HANDLE- ${e}"
